using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;


public class EnemyHealth : MonoBehaviour
{
    [SerializeField] private float intelligence;
    [SerializeField] private float startingHealth = 100;
    private Animator animator;
    [SerializeField] private AudioClip enemyHurt;
    [SerializeField] private AudioSource audioSource;
    [SerializeField] private Slider enemyHealthBarPrefab;
    [SerializeField] private float healthBarOffset;
    private Slider enemyHealthBar;
    private KnockBack knockBack;
    private Enemy enemyScript;
    private Rigidbody2D rb;

    public float currentHealth;
    private bool moveAwayFromPlayer = false;

    private bool knockBacktriggered = false;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();
        if (!animator)
        {
            animator = GetComponentInChildren<Animator>();
        }
        knockBack = GetComponent<KnockBack>();
        enemyScript = GetComponent<Enemy>();
        currentHealth = startingHealth;
        Transform healthRoot = GameObject.Find("EnemyHealthRoot").transform;
        enemyHealthBar = Instantiate(enemyHealthBarPrefab, transform);
        enemyHealthBar.transform.SetParent(healthRoot);
    }

    private void Update()
    {
        if(currentHealth <= 0)
        {
            return;
        }
        Vector3 healthBarPosition = Camera.main.WorldToScreenPoint(transform.position) + new Vector3(0, healthBarOffset, 0);
        enemyHealthBar.transform.position = healthBarPosition;
        enemyHealthBar.value = currentHealth / 100;
        if (!animator.GetBool("Hurting") && knockBacktriggered && !moveAwayFromPlayer)
        {
            StartCoroutine(MoveAwayFromPlayer());
        }
    }

    public void TakeDamage(int damage)
    {
        currentHealth -= damage; 
        checkDetectDeath();
    }

    private void checkDetectDeath()
    {
        if (currentHealth <= 0)
        {
            RewardController.GetInstance().InstantiateReward(transform);
            Destroy(gameObject);
        } else {
            audioSource.PlayOneShot(enemyHurt);
            enemyScript.isAnimating = true;

            StartCoroutine(AnimateHurting());
            knockBack.GetKnockedBack(PlayerController.GetInstance().transform, 30f);
            if (intelligence < 60f)
            {
                enemyScript.isAnimating = false;
                //智商超过60的怪物的机制
                return;
            }
            knockBacktriggered = true;
            //向后撤退一段距离，如果在地图边缘则放弃
            if (transform.position.x > 23f || transform.position.x < -23f)
            {
                return;
            }
            //后退躲避逻辑
            
        }  
    }

    IEnumerator AnimateHurting()
    {
        animator.Play("Hurt");
        animator.SetBool("Hurting", true);
        animator.SetBool("Walking", false);
        animator.ResetTrigger("Attack");
        yield return new WaitForSeconds(1.2f);
        animator.SetBool("Hurting", false);
    }

    private Vector2 moveDir;
    public IEnumerator MoveAwayFromPlayer()
    {
        FlipEnemyWayFromPlayer();
        moveDir = transform.right;
        animator.SetBool("Running", true);
        moveAwayFromPlayer = true;
        yield return new WaitForSecondsRealtime(2f);
        StopMoveAwayFromPlayer();
    }

    public void StopMoveAwayFromPlayer()
    {
        animator.SetBool("Running", false);
        moveAwayFromPlayer = false;
        knockBacktriggered = false;
        enemyScript.isAnimating = false;
    }

    private void FixedUpdate()
    {
        if(moveAwayFromPlayer)
        {
            rb.MovePosition(rb.position + moveDir * (5f * Time.fixedDeltaTime));
        }
    }

    private void FlipEnemyWayFromPlayer()
    {
        Vector3 playerPos = PlayerController.GetInstance().transform.position;

        if (playerPos.x > transform.position.x)
        {
            transform.localEulerAngles = new Vector3(0, 181, 0);
        }
        else
        {
            transform.localEulerAngles = new Vector3(0, 0, 0);
        }
    }




    private void OnDisable()
    {
        Destroy(enemyHealthBar.gameObject);
    }

}
